import { useUserStore } from "@/stores";
import { debounce } from "@/utils/common";
// const getCurrentPagePath = () => {
  // const pages = getCurrentPages();
  // console.log('211111===>', pages[pages.length - 1])
  
  // return pages[pages.length - 1].route;
// }


interface IHttpConfig extends UniApp.RequestOptions {
  loading?: boolean;
  returnCode?: boolean;
  urlType?: keyof typeof urlMap;
}

const userStore = useUserStore();
const urlMap = {
  kaiwu: import.meta.env.VITE_API_KAIWU,
  kdev: import.meta.env.VITE_API_KDEV,
};

const toast = debounce((title: string) => {
  uni.showToast({
    icon: "none",
    duration: 2000,
    title: title,
  });
}, 500);

const success = (options: IHttpConfig, result: any) => {
  const pages = getCurrentPages();
  const currentRoute = pages[pages.length - 1].route
  if (options.returnCode) return result;
  else if (options.urlType === "kaiwu") {
    switch (result.rs) {
      case 200:
        return result.extend;
      default:
        toast(result.msg);
        break;
    }
  } else {
    switch (result.code) {
      case "0":
        return result.data;
      case "10410": // 身份验证信息未提供
      case "10411": // 身份验证信息错误或已过期
        if (currentRoute !== 'pages/my/index') { // 目的是为了校验token是否过期
          toast("请到“我的”登录")
        }
        userStore.clearUserInfo();
        break;
      case "20001": // token过期/失效
        if (currentRoute !== 'pages/my/index') { // 目的是为了校验token是否过期
          toast("请重新登录")
        }
        userStore.clearUserInfo();
        break;
      default:
        toast(result.msg);
        break;
    }
  }
  return Promise.reject(result);
};
success.is = (status: number) => status >= 200 && status < 300;

const initOptions = (options: IHttpConfig) => {
  if (options.loading ?? true) uni.showLoading({ title: "加载中..." });
  if (!options.url.startsWith("http")) {
    options.url = urlMap[options.urlType || "kdev"] + options.url;
  }
  options.timeout ??= Infinity;
  options.header = {
    "request-client": "wechart-app",
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept-Language": "zh",
    Authorization: userStore.token && `JWT ${userStore.token}`,
    // Authorization: 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzM1OTU4NDUzLCJpYXQiOjE3MzU4NzIwNTMsImp0aSI6IjJmMTBjNjU0ZmJjNDQwMDJiNmNkODAzMmEwOTA4N2Q1IiwidXNlcl9pZCI6Nzg0MzY5Mjg2NzU5MDU3Nzd9.LkBy0WfO_8pDNfeiyjZfwGphqy4es6ZLkItjkMtcEp8',
    uid:userStore.userInfo?.uid,
    ...options.header,
  };

  return options;
};

export const http = async (options: IHttpConfig) => {
  try {
    const httpResult = await uni.request(initOptions(options));
    const result: any = httpResult.data;
    if (success.is(httpResult.statusCode)) {
      return success(options, result);
    } else if (httpResult.statusCode === 401) {
      // 401错误  -> 清理用户信息，跳转到登录页
      userStore.clearUserInfo();
      uni.navigateTo({ url: "/pages/login" });
      return Promise.reject(result);
    } else {
      toast(`接口${httpResult.statusCode}异常`);
      return Promise.reject(result);
    }
  } catch (error) {
    toast("网络故障，换个网络试试");
    return Promise.reject(error);
  } finally {
    uni.hideLoading();
  }
};

export const $get = (http.get = (
  url: string,
  config?: Omit<IHttpConfig, "url" | "data"> & { params?: Record<string, any> }
) => {
  return http({
    ...config,
    method: "GET",
    url,
    data: config?.params,
  });
});
export const $post = (http.post = (
  url: string,
  data?: Record<string, any>,
  config?: Omit<IHttpConfig, "url" | "data">
) => {
  return http({
    ...config,
    header: {
      "Content-Type": "application/json",
      ...config?.header,
    },
    method: "POST",
    url,
    data,
  });
});
export const $postForm = (http.postForm = (
  url: string,
  data?: Record<string, any>,
  config?: Omit<IHttpConfig, "url" | "data">
) => {
  return http({
    ...config,
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      ...config?.header,
    },
    method: "POST",
    url,
    data,
  });
});
export const $put = (http.put = (
  url: string,
  data?: Record<string, any>,
  config?: Omit<IHttpConfig, "url" | "data">
) => {
  return http({
    ...config,
    header: {
      "Content-Type": "application/json",
      ...config?.header,
    },
    method: "PUT",
    url,
    data,
  });
});
export const $delete = (http.delete = (
  url: string,
  config?: Omit<IHttpConfig, "url">
) => {
  return http({
    ...config,
    header: {
      "Content-Type": "application/json",
      ...config?.header,
    },
    method: "DELETE",
    url,
  });
});

export default http;

